﻿using System;
using System.Net;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace NS_Client
{
    public class Comms
    {
        private const int BUFFER_SIZE = 4096;

        /// <summary>Sends a HttpPost to the server</summary>
        /// <returns>Server response string</returns>
        /// <param name="message">Message to send</param>
        public static string HttpPost(object message)
        {  


            System.Diagnostics.Debug.WriteLine("------        Sent       ------    " + message);

            WebRequest webRequest = HttpWebRequest.Create(NS_Client.Properties.Settings.Default.Server_URI);
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method = "POST";

            WebClient webClient = new WebClient();

            byte[] bytes = Encoding.ASCII.GetBytes(message.ToString());
            Stream os = null;

            try
            { // send the Post
                webRequest.ContentLength = bytes.Length;   //Count bytes to send
                os = webRequest.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);         //Send it
            }
            catch (WebException ex)
            {
                MessageBox.Show(ex.Message, "HttpPost: Request error",
                   MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            finally
            {
                if (os != null)
                {
                    os.Close();
                }
            }

            try
            { // get the response
                WebResponse response = webRequest.GetResponse();
                if (response == null)
                { return ""; }
                StreamReader sr = new StreamReader(response.GetResponseStream());

                string responseString = sr.ReadToEnd().Trim();


                System.Diagnostics.Debug.WriteLine("------        Reply      ------    " + responseString);

                return responseString;
            }
            catch (Exception ex)
            {
                // System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
            return "";
        }

        public static bool FtpUpload(String filePath)
        {
            string[] SplitPath = filePath.Split('/');
            string fileName = SplitPath[SplitPath.Length - 1];

            FtpWebRequest FtpRequest = (FtpWebRequest)FtpWebRequest.Create(Properties.Settings.Default.FTP_URI + fileName);

            Stream sourceStream = new MemoryStream();
            Stream requestStream = sourceStream;
            //FtpWebResponse FtpResponse;

            try
            {
                FtpRequest.Method = WebRequestMethods.Ftp.UploadFile;
                FtpRequest.Credentials = new NetworkCredential(Properties.Settings.Default.FTP_Username, Properties.Settings.Default.FTP_Password);

                sourceStream = new FileStream(filePath, FileMode.Open);
                requestStream = FtpRequest.GetRequestStream();

                FtpRequest.ContentLength = sourceStream.Length;

                byte[] buffer = new byte[BUFFER_SIZE];
                int bytesRead = sourceStream.Read(buffer, 0, BUFFER_SIZE);

                do
                {
                    requestStream.Write(buffer, 0, bytesRead);
                    bytesRead = sourceStream.Read(buffer, 0, BUFFER_SIZE);

                } while (bytesRead > 0);

                //FtpResponse = (FtpWebResponse)FtpRequest.GetResponse();
                //System.Diagnostics.Debug.WriteLine(FtpResponse.ToString());
                //FtpResponse.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.GetType().Name + ": \n" + ex.Message, "Exception!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            finally
            {
                sourceStream.Close();
                requestStream.Close();
            }

            return true;
        }

        public static void Download(string address, string filename)
        {
            WebClient downloader = new WebClient();
            String location = System.Reflection.Assembly.GetExecutingAssembly().Location;
            char[] assembly_name = (System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".exe").ToCharArray();
            location = (location.TrimEnd(assembly_name) + filename);
            
            downloader.DownloadFile(address, location);
        }
    }
}
